import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * RUNS ONLY ONCE
 */
public class RO_ConvertUSERtoITEM {
	static User[] USER = new User[1000990];
	static Item[] ITEM = new Item[624961];
	static String SER_PATH = "../track1/trainIdx1.txt.sorted" + ".ser";

	public static void main(String[] args) {
		long time;

		time = System.currentTimeMillis();
		readSerialized();
		System.out.println(System.currentTimeMillis() - time);

		time = System.currentTimeMillis();
		createItemArrays();
		System.out.println(System.currentTimeMillis() - time);

		time = System.currentTimeMillis();
		writeSerialisedResult();
		System.out.println(System.currentTimeMillis() - time);
	}

	static void readSerialized() {
		System.out.println("readSerialized: " + SER_PATH);

		try {
			InputStream file = new FileInputStream(SER_PATH);
			InputStream buffer = new BufferedInputStream(file);
			ObjectInput input = new ObjectInputStream(buffer);
			try {
				USER = (User[]) input.readObject();
			} finally {
				input.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void createItemArrays() {
		System.out.println("createItemArrays: " + USER[0]);

		initItemArray();

		for (int userID = 0; userID < USER.length; userID++) {
			User user = USER[userID];

			for (int v = 0; v < user.ilen; v++) {
				int itemID = user.items[v];
				byte vote = user.votes[v];
				ITEM[itemID].put(userID, vote);
			}
		}

		shrinkItems();
	}

	static void initItemArray() {
		for (int i = 0; i < ITEM.length; i++) {
			ITEM[i] = new Item();
		}
	}

	static void shrinkItems() {
		for (int i = 0; i < ITEM.length; i++) {
			ITEM[i].shrink();
		}
	}

	static void writeSerialisedResult() {
		System.out.println("writeSerialisedResult: " + SER_PATH + ".item");

		try {
			OutputStream file = new FileOutputStream(SER_PATH + ".item");
			OutputStream buffer = new BufferedOutputStream(file);
			ObjectOutput output = new ObjectOutputStream(buffer);
			try {
				output.writeObject(ITEM);
			} finally {
				output.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
